<?php
class pro
{
	var $db;
	var $tpl;
	var $page;
	var $pic_save_path;	 
	
	function pro()
	{
		global $db;
		global $config;
		global $point_config;
		global $tpl;		
		$this -> db     = & $db;
		$this -> tpl    = & $tpl;
		$this -> cTime  = date("Y-m-d H:i:s");
		$this->pic_save_path = "";//图片保存目录
		
		
		if(!empty($_POST['title'])||!empty($_POST['title']))
		{
			include_once($config['webroot'].'/includes/filter_class.php');
			$word=new Text_Filter();
			$_POST['detail']=$word->wordsFilter($_POST['detail'], $matche_row);
			/* $_POST['extend_1']=$word->wordsFilter($_POST['extend_1'], $matche_row);
			$_POST['extend_2']=$word->wordsFilter($_POST['extend_2'], $matche_row);
			$_POST['extend_3']=$word->wordsFilter($_POST['extend_3'], $matche_row); */
			$_POST['title']=$word->wordsFilter($_POST['title'], $matche_row);
			
			$_brand=explode('__', $_POST['brand']);
			
			if($_brand[0]&&$_brand[1]){
				$_POST['brand']=$_brand[1];
				$_POST['brandid']=$_brand[0];
			}else{
				$_POST['brand']=$_brand[0];
				$_POST['brandid']=0;
			}
			
			
		}
	}
	
	function get_tax_rate($id)
	{
		//------------------------------------------------------------
		$id=explode(",",$id);
		$re="";
		
		
		if(!empty($id[2]))
		{
			$this->db->query("SELECT tax_rate FROM ".PCAT." WHERE catid='$id[2]'");
			$tax_rate=$this->db->fetchField('tax_rate');
			
			
		}
		if($tax_rate==0&&!empty($id[1]))
		{
			$this->db->query("SELECT tax_rate FROM ".PCAT." WHERE catid='".$id[1]."'");
			$tax_rate=$this->db->fetchField('tax_rate');
		}
		if($tax_rate==0&&!empty($id[0]))
		{
			$this->db->query("SELECT tax_rate FROM ".PCAT." WHERE catid='".$id[0]."'");
			$tax_rate=$this->db->fetchField('tax_rate');
		}
		return $tax_rate;
		
		
	}
	
	
	function get_tags(){
		$sql="select * from ".TAG." where id<9999 order by displayorder,id";
		$this->db->query($sql);
		$de=$this->db->getRows();
		foreach($de as $key=>$val)
		{
			$sql="select * from ".TAG." where id < '".$val['id']."99' and id > '".$val['id']."00' order by displayorder,id";
			$this->db->query($sql);
			$a=$this->db->getRows();
			foreach($a as $ke=>$va)
			{
				$sql="select * from ".TAG." where id < '".$va['id']."99' and id > '".$va['id']."00' order by displayorder,id";
				$this->db->query($sql);
				$b=$a[$ke]['stags']=$this->db->getRows();
				foreach ($b as $k=>$v){
					$sql="select * from ".TAG." where id < '".$v['id']."99' and id > '".$v['id']."00' order by displayorder,id";
					$this->db->query($sql);
					$a[$ke]['stags'][$k]['stags']=$this->db->getRows();
				}
			}
			$de[$key]['stags']=$a;
		}
		return $de;
	}
	
	
	
	
	function get_service($id,$service=NULL)
	{
		//------------------------------------------------------------
		$id=explode(",",$id);
		$re="";
		if(!empty($id[2]))
		{
			$this->db->query("SELECT service FROM ".PCAT." WHERE catid='$id[2]'");
			$service=$this->db->fetchField('service');
		}
		if(empty($service)&&!empty($id[1]))
		{
			$this->db->query("SELECT service FROM ".PCAT." WHERE catid='".$id[1]."'");
			$service=$this->db->fetchField('service');
		}
		if(empty($service)&&!empty($id[0]))
		{
			$this->db->query("SELECT service FROM ".PCAT." WHERE catid='".$id[0]."'");
			$service=$this->db->fetchField('service');
		}
		if(!empty($service))
		{
			$sql="select * from ".SERVICE." where id in ($service) order by id desc ";
			$this->db->query($sql);
			$re=$this->db->getRows();
		}
		return $re;
	}
	
	function get_brand($id,$sbrand=NULL)
	{
		//------------------------------------------------------------
		$id=explode(",",$id);
		if(!empty($id[2]))
			$this->db->query("SELECT brand FROM ".PCAT." WHERE catid='$id[2]'");
		$brand=$this->db->fetchField('brand');
		
		if(empty($brand)&&!empty($id[1]))
		{
			$this->db->query("SELECT brand FROM ".PCAT." WHERE catid='".$id[1]."'");
			$brand=$this->db->fetchField('brand');
		}
		if(empty($brand)&&!empty($id[0]))
		{
			$this->db->query("SELECT brand FROM ".PCAT." WHERE catid='".$id[0]."'");
			$brand=$this->db->fetchField('brand');
		}
		if(!empty($brand))
		{
			$sql="select * from ".BRAND." where id in ($brand) order by displayorder asc ";
			$this->db->query($sql);
			$re=$this->db->getRows();
			$op=NULL;
			foreach($re as $v)
			{
				if($v['name']==$sbrand)
					$s='selected="selected"';
				else
					$s=NULL;
				$op.='<option '.$s.' value="'.$v["id"].'__'.$v["name"].'">'.$v["name"].'</option>';
			}
			return '<select select="select" name="brand" id="brand" />'.$op.'</select>';
		}
		else
			return '<input maxlength="20" type="text" id="brand" name="brand" value="'.$sbrand.'" />';
	}
	
	
	/***zx***********/
/* 	function getCfginfo(){
	    global $config;
	    $returns=array();
	    foreach (array('selltype','sellcat') as $item){
	        if ($config[$item]){
	            $returns[$item]=explode('|', $config[$item]);
	        }
	    }
	    return $returns;
	} */
	
	
	
	
	/*-----------------*/
	
	function getProTypeName($prod)
	{
		if(!empty($prod))
		{
			$sql = "select cat from ".PCAT." where catid in($prod)";
			$this->db->query($sql);
			$fieldlist="";
			while($v=$this->db->fetchRow())
			{
				if($v["cat"]!="")
				$fieldlist.=$v["cat"]."->";
			}
			$fieldlist = trim($fieldlist,"->");
		}
		return $fieldlist;
	}
	
	function add_pro()
	{	
		global $config,$admin,$config;
		include_once("$config[webroot]/includes/tag_inc.php");
		
		$title=$this->real_escape_string($_POST["title"]);
		$ftitle=$this->real_escape_string($_POST["ftitle"]);
		$promotion_tips=$this->real_escape_string($_POST["promotion_tips"]);
		$short_desc=$this->real_escape_string($_POST["short_desc"]);
		
		$_POST['declared_price']*=1;
		$_POST['dis_price']*=1;
		$_POST['freight']*=1;//0为自设定，其它为运费模板。
		$_POST['freight_type']*=1;//1为买家承担，0为卖家承担
		$_POST['weight']*=1;//
		$_POST['cubage']*=1;//
		$_POST['post_price']*=1;
		$_POST['express_price']*=1;
		$_POST['ems_price']*=1;
		$_POST['waiting_time']*=1;
		$_POST['waiting_time_end']*=1;
		$_POST['tags']=@implode(',',$_POST['tags']);
		
		
		/*
		zx
		$_POST["detail"]=replace_outside_link($_POST["detail"]);//过虑内容中的a
		*/
		$_POST['point']*=1;
		$_POST['ptype']=$_POST['ptype']?$_POST['ptype']:"0";
		$_POST['service']=empty($_POST['service'])?NULL:implode(",",$_POST['service']);
		$str=substr($_POST['product_related'],'0','-1');
		$_POST['product_related']=empty($_POST['product_related'])?NULL:$str;
		$str1=substr($_POST['product_give'],'0','-1');
		$_POST['product_give']=empty($_POST['product_give'])?NULL:$str1;
		$str2=substr($_POST['product_parts'],'0','-1');
		$_POST['product_parts']=empty($_POST['product_parts'])?NULL:$str2;
		$times=time();
		
		
		
		$catid=$_POST['catid'];
		$pactidlist=$_POST['catid'];
		if(!empty($_POST['tcatid'])){
			$catid=$_POST['tcatid'];
			$pactidlist.= ",".$_POST['tcatid'];
		}
		if(!empty($_POST['scatid'])){
			$catid=$_POST['scatid'];
			$pactidlist.=",".$_POST['scatid'];
		}
		if(!empty($_POST['sscatid'])){
			$catid=$_POST['sscatid'];
			$pactidlist.=",".$_POST['sscatid'];
		}
		if(empty($_POST['custom_cat'])){
			$_POST['custom_cat']=0;	
		}
		
		//-----产品入库
		
		$pic='';
		$pic_more='';
		$img='';
		$_POST['pic']=array_unique($_POST['pic']);
		if(!empty($_POST['pic']))
		{
			foreach($_POST['pic'] as $val)
			{
				if($val)
				{
					$img[]=$val;	
				}
			}
			if(!empty($img))
			{
				$pic=$img['0'];
				$pro_img=$img;
				$pic_more=implode(',',$img);
			}
			
		}
		
		
		$sql="INSERT INTO ".PRO." (create_user,catid,tags,pname,brandid,brand,pic,promotion_tips,keywords,detail,price,market_price,tax_rate,unit,product_related,product_give,product_parts,province,city,areaid,area,weight,cubage,status,property_id,waiting_time,waiting_time_end,short_desc,pic_more,stock_shop,hscode,tax_paid_price,guojia,guojiapic,province1,distribution,distribution1)
		VALUES
			('$_SESSION[ADMIN_USER]','$catid','$_POST[tags]','$title',
		'$_POST[brandid]','$_POST[brand]','$pic','$_POST[promotion_tips]'
		,'$_POST[keywords]','$_POST[detail]','$_POST[price]','$_POST[market_price]','$_POST[tax_rate]','$_POST[unit]','$_POST[product_related]','$_POST[product_give]','$_POST[product_parts]','$_POST[province]','$_POST[city]','$_POST[area]','$_POST[t]','$_POST[weight]','$_POST[cubage]',".($_POST['tocheck']?-2:0).",'$_POST[property_id]','$_POST[waiting_time]','$_POST[waiting_time_end]','$short_desc','$pic_more','$_POST[stock_shop]','$_POST[hscode]','$_POST[tax_paid_price]','$_POST[guojia]','$_POST[guojiapic]','$_POST[province1]','$_POST[distribution]','$_POST[distribution1]')";
		$re=$this->db->query($sql);
		$id=$this->db->lastid();
		
		//zx
		
		$_POST['code']=$_POST['catid'].str_pad($id, 6,'0',STR_PAD_LEFT);
		
		$this->db->query("update ".PRO." set code='{$_POST['code']}' where id={$id} limit 1");//zx更新 母表的code 不用改变
		//
		/* $re=$this->db->query("INSERT INTO ".PRODETAIL." (userid,proid,after_service,extend_1,extend_2,extend_3) VALUES ('0','$id','$_POST[after_service]','$_POST[extend_1]','$_POST[extend_2]','$_POST[extend_3]')");
		 */
		$i=0;
		if(!empty($_POST['spec']))
		{
			foreach($_POST['spec'] as $key=>$v)
			{
				$str1 = array();
				$str2 = array();
				$img=$pro_img;
				foreach($v['sp_value'] as $val)
				{
					foreach($val as $num=>$s)
					{
						if(!empty($num)){
							$str1[] = $s;
						}
						$str2[] = $num;
					}
					
				}
				
				if($v['color']&&$_POST['color_img'][$v['color']])
				{
					unset($img[@array_search($_POST['color_img'][$v['color']], $img)]);
					array_unshift($img,$_POST['color_img'][$v['color']] );
				}
				$pic_more=implode(',',$img);
				$name=implode(' ',$str1);
				$pids=implode(',',$str2);
				
				$code =$_POST['code'];
				
				if(!empty($v))
				{
					
					$title1='';
					$v['price']=$v['price']?$v['price']*1:"0.00";
					$v['declared_price']=$v['declared_price']?$v['declared_price']*1:"0.00";
					$v['dis_price']=$v['dis_price']?$v['dis_price']*1:"0.00";
					$v['weight']=$v['weight']?$v['weight']*1:$_POST['weight'];
					$title1=$title."($name)";
					
					if($i+1<10){
						
						$code.='0'.($i+1);
					}else{
						$code.=($i+1);
					}
					
					$sql="insert into ".SETMEAL." 
					(pid,code,pname,price,declared_price,dis_price,stock,stock_relations,buy_limit,property_value_id,catid,promotion_tips,brandid,brand,pic,province,city,areaid,area,uptime,status,create_user,tax_rate,market_price,spec,weight,cubage,tags,stock_shop,tax_paid_price,guojia,guojiapic,province1,distribution,distribution1)
					values 
					('$id','$code','".$title."','".$v['price']."','".$v['declared_price']."','".$v['dis_price']."','$v[stock]','1','".$v['buy_limit']."','".$pids."','$catid','$promotion_tips','$_POST[brandid]','$_POST[brand]','$pic_more','$_POST[province]','$_POST[city]','$_POST[area]','$_POST[t]','$times',".($_POST['tocheck']?-2:0).",'$_SESSION[ADMIN_USER]','$_POST[tax_rate]','$v[market_price]','$name','$v[weight]','$_POST[cubage]','$_POST[tags]','$_POST[stock_shop]','$_POST[tax_paid_price]','$_POST[guojia]','$_POST[guojiapic]','$_POST[province1]','$_POST[distribution]','$_POST[distribution1]')";
					$this->db->query($sql);
				}
				$i++;
			}
		}
		else
		{
			$code=$_POST['code'].'00';
			$sql="insert into ".SETMEAL." 
			(pid,code,pname,price,declared_price,dis_price,stock,stock_relations,buy_limit,property_value_id,catid,promotion_tips,brandid,brand,pic,province,city,areaid,area,uptime,status,create_user,tax_rate,market_price,weight,cubage,tags,stock_shop,tax_paid_price,guojia,guojiapic,province1,distribution,distribution1)
			values 
			('$id','$code','".$title."','".$_POST['price']."','".$_POST['declared_price']."','".$_POST['dis_price']."','".$_POST['stock']."','1','".$_POST['buy_limit']."','','$catid','$promotion_tips','$_POST[brandid]','$_POST[brand]','$pic_more','$_POST[province]','$_POST[city]','$_POST[area]','$_POST[t]','$times',".($_POST['tocheck']?-2:0).",'$_SESSION[ADMIN_USER]','$_POST[tax_rate]','$_POST[market_price]','$_POST[weight]','$_POST[cubage]','$_POST[tags]','$_POST[stock_shop]','$_POST[tax_paid_price]','$_POST[guojia]','$_POST[guojiapic]','$_POST[province1]','$_POST[distribution]','$_POST[distribution1]')";
			$this->db->query($sql);
		}
		//--------------------更新关键词
		/* add_tags($_POST['keyword'],1,$id); */
		
		//-----------------单sku回写
		$this->update_single_sku_id($id);
		
		//--------------------填加自定义字段
		$sql="select ext_table from ".PCAT." where catid='$catid'";
		$this->db->query($sql);
		$ext_table=$this->db->fetchField('ext_table');
		
		include_once("$config[webroot]/module/product/includes/plugin_add_field_class.php");
		$addfield = new AddField('product');
		$addfield->update_con($id,$ext_table);
		$addfield->update_default_con($id);
		//---------------------
		return $id;
	}

	function edit_pro()
	{
		global $config,$admin,$config;
		include_once("$config[webroot]/includes/tag_inc.php");
		
		$title=$this->real_escape_string($_POST["title"]);
		$ftitle=$this->real_escape_string($_POST["ftitle"]);
		$promotion_tips=$this->real_escape_string($_POST["promotion_tips"]);
		$short_desc=$this->real_escape_string($_POST["short_desc"]);
		
		$catid=$_POST['catid'];
		$pactidlist= $_POST['catid'];
		$id=$_POST["editID"]*1;
		$_POST['declared_price']*=1;
		$_POST['freight']*=1;//0为自设定，其它为运费模板。
		$_POST['freight_type']*=1;//1为买家承担，0为卖家承担
		$_POST['weight']*=1;//重量
		$_POST['cubage']*=1;//体积
		$_POST['post_price']*=1;
		$_POST['express_price']*=1;
		$_POST['ems_price']*=1;
		$_POST['point']*=1;
		$_POST['ptype']*=1;
		$_POST['waiting_time']*=1;
		$_POST['waiting_time_end']*=1;
		$_POST['price']=$_POST['price']?$_POST['price']:($_POST['setmeal_p'][0]?$_POST['setmeal_p'][0]:$_POST['setmeal_p1'][0]);
		
		//zx库存
		$_POST['service']=empty($_POST['service'])?NULL:implode(",",$_POST['service']);
		$str=substr($_POST['product_related'],'0','-1');
		$_POST['product_related']=empty($_POST['product_related'])?NULL:$str;
		$str1=substr($_POST['product_give'],'0','-1');
		$_POST['product_give']=empty($_POST['product_give'])?NULL:$str1;
		$str2=substr($_POST['product_parts'],'0','-1');
		$_POST['product_parts']=empty($_POST['product_parts'])?NULL:$str2;
		
		$_POST['tags']=@implode(',',$_POST['tags']);
	    $_POST['code']=$_POST['catid'].str_pad($id, 6,'0',STR_PAD_LEFT);
		
		
		
		$times=time();
		if(empty($catid)||empty($title))
			return 'Error';
		
		if(!empty($_POST['tcatid'])){
			$catid=$_POST['tcatid'];
			$pactidlist.= ",".$_POST['tcatid'];
		}
		if(!empty($_POST['scatid'])){
			$catid=$_POST['scatid'];
			$pactidlist.= ",".$_POST['scatid'];
		}
		if(!empty($_POST['sscatid'])){
			$catid=$_POST['sscatid'];
			$pactidlist.= ",".$_POST['sscatid'];
		}	
		if(empty($_POST['custom_cat'])){
			$_POST['custom_cat']=0;	
		}

		$sub_sql = $sub_sql_2='';
		$pic='';
		$pic_more='';
		$img=array();
		$_POST['pic']=array_unique($_POST['pic']);
		if(!empty($_POST['pic']))
		{
			foreach($_POST['pic'] as $val)
			{
				if($val)
				{
					$img[]=$val;	
				}
			}

				$pic=$img['0'];
				$pro_img=$img;
				$pic_more=implode(',',$img);
		}
		
		//状态
		
		
		if($_POST['statu']==-1||$_POST['statu']==0){
		    if($_POST['tocheck']){
		        $_POST['statu']=-2;
		    }
		}
		
		
		  $sql="UPDATE ".PRO."  
			SET status=".$_POST['statu'].",
			pname='$title',
			catid='$catid',
			brandid='$_POST[brandid]',
			brand='$_POST[brand]',
			keywords='$_POST[keywords]',
			promotion_tips='$promotion_tips',			
			short_desc='$short_desc',			
			price='$_POST[price]',
			market_price='$_POST[market_price]',
			tax_rate='$_POST[tax_rate]',
			detail ='$_POST[detail]',
			unit ='$_POST[unit]',
			product_related ='$_POST[product_related]',
			product_give ='$_POST[product_give]',
			product_parts ='$_POST[product_parts]',
		    province='$_POST[province]',
			city='$_POST[city]',
			area='$_POST[t]',
			areaid='$_POST[area]',
			cubage='$_POST[cubage]' ,
			weight='$_POST[weight]' ,
			waiting_time='$_POST[waiting_time]' ,
			waiting_time_end='$_POST[waiting_time_end]' ,
			tags='$_POST[tags]',
			pic='$pic',
			pic_more='$pic_more',
			property_id='$_POST[property_id]',
			stock_shop = '$_POST[stock_shop]',
			hscode ='$_POST[hscode]',
			tax_paid_price ='$_POST[tax_paid_price]',
			guojia = '$_POST[guojia]',
			guojiapic = '$_POST[guojiapic]',
			province1 = '$_POST[province1]',
			distribution = '$_POST[distribution]',
			distribution1 = '$_POST[distribution1]'
			WHERE id=$id ";
		 $this->db->query($sql);
		
		if(!empty($_POST['spec']))
		{//有规格的情况
			$sql="select property_value_id,id,code,status from ".SETMEAL." where pid = '$id' order by code desc";
			$this->db->query($sql);
			$re=$this->db->getRows();//原有的规格情况
			$i=1;
			$max_code=$re[0]['code'];
	
			foreach($_POST['spec'] as $key=>$v)
			{
				$str1 = array();
				$str2 = array();
				$str_not_empty=array();
				$img=$pro_img;
				foreach($v['sp_value'] as $k=>$val)
				{
					foreach($val as $num=>$s)
					{
						if(!empty($num)){
							$str1[] = $s;
							$str_not_empty[] = $num;
						}
						$str2[] = $num;
					}				
				}
				
				if($v['color']&&$_POST['color_img'][$v['color']])
				{
					unset($img[@array_search($_POST['color_img'][$v['color']], $img)]);
					array_unshift($img,$_POST['color_img'][$v['color']] );
				}
				$pic_more=implode(',',$img);
				
				$name=implode(' ',$str1);
				$pids=implode(',',$str2);
				$pid_not_empty=implode(',', $str_not_empty);
				$pid2[]=$pids;
				if (!in_array($pid_not_empty, $pid2)){
					$pid2[]=$pid_not_empty;
				}
				
				$sql="select id from ".SETMEAL." where pid = '$id' and (property_value_id='$pids' or property_value_id='$pid_not_empty' and spec='$name')";
				$this->db->query($sql);
				$setmeal_id=$this->db->fetchField('id');
				if(!empty($v))
				{
					$title1='';
					$v['price']=$v['price']?$v['price']*1:"0.00";
					$v['declared_price']=$v['declared_price']?$v['declared_price']*1:"0.00";
					$v['dis_price']=$v['dis_price']?$v['dis_price']*1:"0.00";
					$v['weight']=$v['weight']?$v['weight']*1:$_POST['weight'];
					$title1=$title."($name)";
					if($setmeal_id)
					{//如果原有此规格 进行更改
						
						//pid,code,pname,price,declared_price,dis_price,stock,stock_relations,property_value_id,catid,promotion_tips,brandid,brand,pic,province,city,areaid,area,uptime,status,create_user,tax_rate,market_price
						
						$sql="UPDATE ".SETMEAL."  SET status=".$_POST['statu']." ,
						pname='$title',
						promotion_tips='$promotion_tips',
						catid='$catid',
						brandid='$_POST[brandid]',
						brand='$_POST[brand]',
						declared_price='$v[declared_price]',
						dis_price='$v[dis_price]',
						price='$v[price]',
						uptime='$times',
						province='$_POST[province]',
						city='$_POST[city]',
						area='$_POST[t]',
						areaid='$_POST[area]',
						buy_limit='$v[buy_limit]' ,
						stock_relations='1' ,
						market_price='$v[market_price]' ,
						tax_rate='$_POST[tax_rate]' ,
						cubage='$_POST[cubage]' ,
						weight='$v[weight]' ,
						tags='$_POST[tags]',
						spec = '$name',
						property_value_id = '$pids',
						pic = '$pic_more',
						stock_shop = '$_POST[stock_shop]',
						tax_paid_price ='$_POST[tax_paid_price]',
						guojia = '$_POST[guojia]',
			             guojiapic = '$_POST[guojiapic]',
			             province1 = '$_POST[province1]',
						distribution = '$_POST[distribution]',
						distribution1 = '$_POST[distribution1]'
						WHERE id='$setmeal_id'";
						$this->db->query($sql);
					}
					else
					{//没有此规格增加
						
						$code =$max_code+$i;					
						
						$sql="insert into ".SETMEAL."
						(pid,code,pname,price,declared_price,dis_price,stock_relations,buy_limit,property_value_id,catid,promotion_tips,brandid,brand,pic,province,city,areaid,area,uptime,status,create_user,tax_rate,market_price,spec,weight,cubage,tags,stock_shop,tax_paid_price,guojia,guojiapic,province1,distribution,distribution1)
						values
						('$id','$code','".$title."','".$v['price']."','".$v['declared_price']."','".$v['dis_price']."','1','".$v['buy_limit']."','".$pids."','$catid','$promotion_tips','$_POST[brandid]','$_POST[brand]','$pic_more','$_POST[province]','$_POST[city]','$_POST[area]','$_POST[t]','$times',".($_POST['statu']).",'$_SESSION[ADMIN_USER]','$_POST[tax_rate]','$_POST[market_price]','$name','$v[weight]','$_POST[cubage]','$_POST[tags]','$_POST[stock_shop]','$_POST[tax_paid_price]','$_POST[guojia]','$_POST[guojiapic]','$_POST[province1]','$_POST[distribution]','$_POST[distribution1]')";
						$this->db->query($sql);
					$i++;
					}
				}
			}
			foreach($re as $vs)
			{
				if ($vs['status']=='-9')continue;
				if(!in_array($vs['property_value_id'],$pid2))
				{
					$str3[]=$vs['id'];	
				}
			}
			if(!empty($str3))
			{//把不在此规格的全部删掉
				$pid1=implode(',',$str3);	
				$sql="update ". SETMEAL ." set status=-9 WHERE `id` in ($pid1) ";
				$this->db->query($sql);	
			}
		}
		else
		{//没规格的情况
			
			$sql="update ". SETMEAL ." set status=-9 WHERE  pid = '$id' and `property_value_id` != '' ";//如果原来有规格删掉规格
			$this->db->query($sql);	
				
			$sql="select id from ".SETMEAL." where pid = '$id' and `property_value_id` = ''" ;//如果原来存在默认规格
			$this->db->query($sql);
			$setmeal_id=$this->db->fetchField('id');
			if($setmeal_id)
			{
						 $sql="UPDATE ".SETMEAL."  SET status=".$_POST['statu']." ,
						pname='$title',
						promotion_tips='$promotion_tips',
						catid='$catid',
						brandid='$_POST[brandid]',
						brand='$_POST[brand]',
						declared_price='$_POST[declared_price]',
						dis_price='$_POST[dis_price]',
						price='$_POST[price]',
						uptime='$times',
						province='$_POST[province]',
						city='$_POST[city]',
						area='$_POST[t]',
						areaid='$_POST[area]',
						stock_relations='1' ,
						buy_limit='$_POST[buy_limit]' ,
						market_price='$_POST[market_price]' ,
						tax_rate='$_POST[tax_rate]' ,
						cubage='$_POST[cubage]' ,
						weight='$_POST[weight]' ,
						tags='$_POST[tags]',
						spec = '$name',
						pic = '$pic_more' ,
						stock_shop = '$_POST[stock_shop]',
						tax_paid_price ='$_POST[tax_paid_price]',
						guojia = '$_POST[guojia]',
			             guojiapic = '$_POST[guojiapic]',
						province1 = '$_POST[province1]',
						distribution = '$_POST[distribution]',
						distribution1 = '$_POST[distribution1]'
						 WHERE id='$setmeal_id'";
						$this->db->query($sql);
			}
			else
			{
				$_POST['code'].='00';
				$sql="insert into ".SETMEAL."
				(pid,code,pname,price,declared_price,dis_price,stock_relations,buy_limit,property_value_id,catid,promotion_tips,brandid,brand,pic,province,city,areaid,area,uptime,status,create_user,tax_rate,market_price,weight,cubage,tags,stock_shop,tax_paid_price,guojia,guojiapic,province1,distribution,distribution1)
				values
				('$id','$_POST[code]','".$title."','".$_POST['price']."','".$_POST['declared_price']."','".$_POST['dis_price']."','1','".$_POST['buy_limit']."','','$catid','$promotion_tips','$_POST[brandid]','$_POST[brand]','$pic_more','$_POST[province]','$_POST[city]','$_POST[area]','$_POST[t]','$times',".($_POST['statu']).",'$_SESSION[ADMIN_USER]','$_POST[tax_rate]','$_POST[market_price]','$_POST[weight]','$_POST[cubage]','$_POST[tags]','$_POST[stock_shop]','$_POST[tax_paid_price]','$_POST[guojia]','$_POST[guojiapic]','$_POST[province1]','$_POST[distribution]','$_POST[distribution1]')";
				$this->db->query($sql);
			}
		}
		
		//-----------------更新产品详情
/* 		$sql="select proid from ".PRODETAIL." where proid='$id'";
		$this->db->query($sql);
		if($this->db->num_rows())
			$re=$this->db->query("UPDATE ".PRODETAIL." SET detail='$_POST[detail]',extend_1='$_POST[extend_1]',extend_2='$_POST[extend_2]',extend_3='$_POST[extend_3]',after_service='$_POST[after_service]' WHERE proid='$id'");
		else
			$re=$this->db->query("INSERT INTO ".PRODETAIL." (userid,proid,detail,extend_1,extend_2,extend_3) VALUES ('0','$id','$_POST[detail]','$_POST[extend_1]','$_POST[extend_2]','$_POST[extend_3]')");
			 */
		//--------------------添加关键词
		//edit_tags($_POST['keyword'],1,$id);
		
		//-----------------单sku回写
		$this->update_single_sku_id($id);
		
		//--------------------填加自定义字段
		$sql="select ext_table from ".PCAT." where catid='$catid'";
		if($this->db->query($sql)){
			$ext_table=$this->db->fetchField('ext_table');
		}
		include_once("$config[webroot]/module/product/includes/plugin_add_field_class.php");
		$addfield = new AddField('product');
		$addfield->update_con($id,$ext_table);
		$addfield->update_default_con($id);
		//---------------------
		return $id;
	}
	
	function pro_detail($id)
	{
		if($id)
		{	
			global $config;
			include_once("$config[webroot]/includes/tag_inc.php");
			//$sql="select a.*,b.detail,b.extend_1,b.extend_2,b.extend_3,b.after_service from ".PRO." a left join ".PRODETAIL." b on a.id=b.proid where a.id=$id and a.userid='0'";
			$sql="select a.* from ".PRO." a  where a.id=$id limit 1";
				
			$this->db->query($sql);
			$re=$this->db->fetchRow();
			
			$sql="select ext_table from ".PCAT." where catid='$re[catid]'";
			$this->db->query($sql);
			$re['ext_table']=$this->db->fetchField('ext_table');
			
			if(strlen($re['catid'])>8)
				$re['sscatid']=$re['catid'];
			if(strlen($re['catid'])>6)
				$re['scatid']=substr($re['catid'],0,8);	
			if(strlen($re['catid'])>4)
				$re['tcatid']=substr($re['catid'],0,6);
			$re['catid']=substr($re['catid'],0,4);
			
			
			
			
			$sql="select * from ".SETMEAL." where pid=$id and status>-9";
			$this->db->query($sql);
			$re['porperty']=$this->db->getRows();
			
			//定义多sku取值的规则
		    $multipleSku=array('dis_price'=>'min','declared_price'=>'min','stock'=>'min','buy_limit'=>'min','property_value_id'=>'any');
			
			foreach($re['porperty'] as $key=>$val)
			{
			    $a=explode(' ',$val['spec']);
			    $b=explode(',',$val['property_value_id']);
			    $c=array();
			    $d='';
			    foreach($b as $k=>$v)
			    {
			    	if($v){
			        $num=$v;
			        $c[$k][$num]=$a[$k];
			        $d.=$num;
			    	}
			    }
			    $re['porperty'][$key]['setmeal']=$c;
			    $re['porperty'][$key]['property_value_id']=$d;
			    foreach ($val as $itemkey=>$itemVal){
			        if ($multipleSku[$itemkey]){
			            switch ($multipleSku[$itemkey]){
			                case 'min':
			                    if($re[$itemkey]>$itemVal||!isset($re[$itemkey])){
			                        $re[$itemkey]=$itemVal;
			                    }
			                    break;
			                case 'max':
			                    if ($re[$itemkey]<$itemVal||!isset($re[$itemkey])){
			                        $re[$itemkey]=$itemVal;
			                    }
			                    break;
			                case 'first':
			                    if ($key==0){
			                        $re[$itemkey]=$itemVal;
			                    }
			                    break;
			                case 'any':
			                    default:
			                      if (!isset($re[$itemkey])){
			                          $re[$itemkey]=$itemVal;
			                      }
			            }
			            
			        }
			    }
			}
			//echo '<pre>';
			
// var_dump($re);
// exit;			
// 			//////////////////////*************冗余的sku 赋值给主************////
			
// 			foreach (array('dis_price','declared_price','stock','buy_limit','property_value_id',) as $item){
				
// 				$re[$item]=$re['porperty'][0][$item];
				
// 			}
			
			
			
			
			
			//////////////////////////////////////////////////
			
			
			
			
			
			
			//=====================================
		
			//$re['keyword']=get_tags($id,1);
			//======================================
			
			$re['pic'] = $re['pic_more']?explode(',',$re['pic_more']):'';
			
			$re['tags'] =$re['tags']?@explode(',',$re['tags']):array();
			$re['services'] = $re['service']?explode(',',$re['service']):'';
			$re['product_related_id'] = $re['product_related']?explode(',',$re['product_related']):'';
			$re['product_give_id'] = $re['product_give']?explode(',',$re['product_give']):'';
			$re['product_parts_id'] = $re['product_parts']?explode(',',$re['product_parts']):'';
			if($re['product_related_id'])
			{
				foreach($re['product_related_id'] as $key=>$val)
				{
					if($val)
					{
						$sql="SELECT id,tags,catid,brand,pic,pname,price,market_price, code  FROM ".PRO." where id='$val' and status>-9 order by id desc";
						$this->db->query($sql);
						$aa[$key]=$this->db->fetchRow();
						$tmp=array();
						if ($aa[$key]['catid']){
							$sql = "select cat from ".PCAT." where '{$aa[$key]['catid']}' like concat(`catid`,'%')  order by catid asc";
							$this->db->query($sql);
							foreach ($cat=$this->db->getRows() as $item){
								$tmp[]=$item['cat'];
							}
							$aa[$key]['catname']=implode(' ', $tmp);
						}
						$tmp=array();
						if ($aa[$key]['tags']){
							$sql =" select tags from " .TAG ." where id in ({$aa[$key]['tags']}) order by id asc";
							$this->db->query($sql);
							foreach ($tags=$this->db->getRows() as $item){
								$tmp[]=$item['tags'];
							}
							$aa[$key]['tags']=implode(' ', $tmp);
								
						}
						
					}
				}
				$re['product_relateds']=$aa;
			}
			if($re['product_give_id'])
			{
				foreach($re['product_give_id'] as $key=>$val)
				{
					if($val)
					{
						$sql="SELECT id,tags,catid,brand,pic,pname,price,market_price, code  FROM ".PRO." where id='$val' and status>-9 order by id desc";
						$this->db->query($sql);
						$bb[$key]=$this->db->getRows();
					}
				}
				$re['product_gives']=$bb;
			}
			if($re['product_parts_id'])
			{
				foreach($re['product_parts_id'] as $key=>$val)
				{
					if($val)
					{
						$sql="SELECT id,tags,catid,brand,pic,pname,price,market_price, code  FROM ".PRO." where id='$val' and status>-9 order by id desc";
						$this->db->query($sql);
						$cc[$key]=$this->db->getRows();
					}
				}
				$re['product_partss']=$cc;
			}
			
			$re['product_related_id'] = $re['product_related']?explode(',',$re['product_related']):'';
			$re['product_give_id'] = $re['product_give']?explode(',',$re['product_give']):'';
			$re['product_parts_id'] = $re['product_parts']?explode(',',$re['product_parts']):'';
			
			return $re;
		}
	}
	//==============================
	function detail($pid)
	{
		global $config;
		$sql="select 
		a.*,
		c.detail
		from 
		".SETMEAL." a left join 
		".PRO." c on a.pid=c.id 
		where a.id='$pid' and a.status>-9";
		$this->db->query($sql);
		$prod=$this->db->fetchRow();
		if($prod['service'])
		{
			$sql="SELECT * FROM ".SERVICE." where id in ($prod[service]) order by id desc";
			$this->db->query($sql);
			$prod['service']=$this->db->getRows();
		}
		if($prod['product_give'])
		{
			$sql="SELECT id,pic,pname FROM ".SETMEAL." where id in ($prod[product_give]) and status>-9 order by id desc";
			$this->db->query($sql);
			$prod['product_gives']=$this->db->getRows();
		}
		if($prod['product_parts'])
		{
			$sql="SELECT id,pid,pic,pname,price,dis_price,sku as code FROM ".SETMEAL." where id in ($prod[product_parts]) and statu>-9 order by id desc";
			$this->db->query($sql);
			$prod['product_partss']=$this->db->getRows();
		}
		$sql="select * from ".SETMEAL." where pid=$prod[pid] and status>-9 and property_value_id !='' ";
		$this->db->query($sql);
		$prod['porperty']=$this->db->getRows();
		foreach($prod['porperty'] as $key=>$val)
		{
			$a=explode(',',$val['setmeal']);
			$b=explode(',',$val['property_value_id']);
			$c=array();
			$d='';
			foreach($a as $k=>$v)
			{
				$num=$b[$k];
				$c[$k][$num]=$v;
				$d[]=$num;
			}
			$re['porperty'][$key]['setmeal']=$c;
			$re['porperty'][$key]['property_value_id']=$d;
		}
		if(!empty($prod['pic'])){
			$prod['pic_more'] = explode(",",$prod['pic_more']);		
		}
		return $prod;
	}
	
	function get_comment_count($id)
	{
		$sql="select count(*) as count from ".PCOMMENT." where product_id='$id'";
		$this->db->query($sql);
		$count=$this->db->fetchfield("count");	
		return $count;
	}
	function get_comment($id,$goodbad=NULL,$count='0')
	{
		if(!empty($goodbad)){
		$scl.=" and goodbad in($goodbad)";
		}
		$sql="select count(*) as count from ".PCOMMENT." where product_id='$id' $scl";
		$this->db->query($sql);
		$num=$this->db->fetchfield("count");
		$persent=$count==0?($goodbad=='4,5'?'100':"0"):$num/$count*100;
		return array($persent,$num);
	}
	function real_escape_string($string){
		if(get_magic_quotes_gpc()){
			return $string;
		}else{
			return mysql_real_escape_string(stripcslashes($string));
		}
	}
	
	function get_stock_shops(){//发货库房
		$sql ="select * from " .STOCKSHOP. " where 1";
		
		$this->db->query($sql);
		$stock_shops=$this->db->getRows();
		return $stock_shops;
	}
	
	function update_single_sku_id($pid){
	    $sql="select  id  from ".SETMEAL." where status>0 and pid = ".$pid;
	    $this->db->query($sql);
	    if ($skus=$this->db->getRows()){
	        if(count($skus)==1){
	            $this->db->query("update ".PRO." set single_sku_id=".$skus[0]['id'] ." where id=".$pid. " limit 1");
	        }else{
	            $this->db->query("update ".PRO." set single_sku_id=0 where id=".$pid. "  limit 1");
	        }
	    }
	}
	
	/**
	 * 获取商品税费
	 * @param array $idArr array(array('id'=>159,'num'=>2))
	 */
	function get_products_rate_price($idArr){
		global $config,$admin;
		include($config['webroot'].'/lang/cn/company_type_config.php');
		$price_rate = $price_rate_config['euro'];
		$default_rate = 0.1;
		$price = 0;
		$res = array();
		if(!empty($idArr)){
			$ids = "";
			$numArr = array();
			foreach ($idArr as $v)
			{
				if(empty($ids)){
					$ids .= $v['id'];
				}else{
					$ids .= ",".$v['id'];
				}
				$numArr[$v['id']] = $v['num'];
			}
			$ids = trim($ids,',');
			if(!empty($ids)){
				$sql = "select a.min_realpricebuy,a.product_sku_id,c.tax_rate,d.tax_rate as cat_tax_rate from haiou_stock_products as a left join haiou_product_sku as b on a.product_sku_id=b.id join haiou_products as c on b.pid=c.id join haiou_product_cat as d on d.catid=c.catid where a.product_sku_id in({$ids})";
				$this->db->query($sql);
				$res = $this->db->getRows();
				if(!empty($res)){
					foreach ($res as $val)
					{
						$rate = ($val['tax_rate']>0)?$val['tax_rate']:(($val['cat_tax_rate']>0)?$val['cat_tax_rate']:$default_rate);
						$price += $val['min_realpricebuy']*$rate*$numArr[$val['product_sku_id']];
					}
				}
			}
			$price = round($price*$price_rate,2);
		}
		
		return array('price'=>$price,'products'=>$res);
	}
	
	/**
	 * 获取海关分类
	 */
	function get_product_cat_customs($hscode=''){
		$cats = array();
		if(!empty($hscode)){
			$sql="select * from ".PCATCUSTOMS." where hscode='{$hscode}'";
			$this->db->query($sql);
			$cats=$this->db->fetchRow();
			return $cats;
		}
		$sql="select * from ".PCATCUSTOMS." where catid<9999 order by displayorder,catid";
		$this->db->query($sql);
		$cats=$this->db->getRows();
		foreach($cats as $key=>$val)
		{
			$sql="select * from ".PCATCUSTOMS." where catid < '".$val['catid']."99' and catid > '".$val['catid']."00' order by displayorder,catid";
			$this->db->query($sql);
			$a=$this->db->getRows();
			foreach($a as $ke=>$va)
			{
				$sql="select * from ".PCATCUSTOMS." where catid < '".$va['catid']."99' and catid > '".$va['catid']."00' order by displayorder,catid";
				$this->db->query($sql);
				$a[$ke]['scat']=$this->db->getRows();
				foreach ($a[$ke]['scat'] as $kk=>$vv)
				{
					$sql="select * from ".PCATCUSTOMS." where catid < '".$vv['catid']."99' and catid > '".$vv['catid']."00' order by displayorder,catid";
					$this->db->query($sql);
					$d = $this->db->getRows();
					foreach ($d as $dk=>$dv)
					{
					    $sql="select * from ".PCATCUSTOMS." where catid < '".$dv['catid']."99' and catid > '".$dv['catid']."00' order by displayorder,catid";
					    $this->db->query($sql);
					    $d[$dk]['scat']=$this->db->getRows();
					}
					$a[$ke]['scat'][$kk]['scat']=$d;
				}
			}
			$cats[$key]['scat']=$a;
		}
		
		return $cats;
	}
}


?>